LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_unsigned.all;

ENTITY switch_test_cntrl IS
	PORT (
		--THESE PORTS SHOULD BE PORTMAPPED TO PHYSICAL PINS
		clk_50		: IN STD_LOGIC;
		test_en_n	: IN STD_LOGIC;
		mode_en_n	: IN STD_LOGIC;
		switch_rdy	: IN STD_LOGIC;
		rd_addr		: IN STD_LOGIC_VECTOR(3 DOWNTO 0);
		reset_n		: IN STD_LOGIC;
		
		--
		mem_ptr		: OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
		ram_en		: OUT STD_LOGIC := '1';
		rom_en		: OUT STD_LOGIC := '1';
		lookup_req	: OUT STD_LOGIC;
		wr_rslt_en	: OUT STD_LOGIC
	);
END switch_test_cntrl;

ARCHITECTURE Behavior OF switch_test_cntrl IS
	TYPE State_type IS (IDLE, PAUSE, READ, WRITE, TEST);
	SIGNAL y : State_type := IDLE;
	SIGNAL ramrom_addr : STD_LOGIC_VECTOR(3 DOWNTO 0) := (OTHERS => '0');
	SIGNAL test_index : INTEGER RANGE 0 TO 15 := 0;
	SIGNAL test_delay : STD_LOGIC_VECTOR(25 DOWNTO 0) := (OTHERS => '0');
	SIGNAL writing : STD_LOGIC_VECTOR(1 DOWNTO 0) := "11";
BEGIN
	PROCESS (clk_50)
	BEGIN
		IF (clk_50'EVENT AND clk_50='1') THEN
			IF (reset_n = '0') THEN
				y <= IDLE;
			END IF;
			IF (y = IDLE) THEN
				--IDLE
				ram_en <= '1';
				rom_en <= '1';
				ramrom_addr <= "0000";
				lookup_req <= '0';
				wr_rslt_en <= '0';
				test_delay <= (OTHERS => '0');
				writing <= "00";
								
				IF (test_en_n = '0') THEN
					IF (mode_en_n = '0') THEN
						mem_ptr <= ramrom_addr;
						--y <= TEST;
						y <= PAUSE;
					ELSE
						mem_ptr <= rd_addr;
						y <= READ;
					END IF;
				END IF;
			ELSIF (y = PAUSE) THEN
				--wait
				IF (test_delay = X"FFFFFF") THEN --X"2FAF080" = 1 sec@50MHz****
					test_delay <= (OTHERS => '0');
					y <= TEST;
				ELSE
					test_delay <= test_delay + 1;
				END IF;
			ELSIF (y = WRITE) THEN
					lookup_req <= '0';
					--wr_rslt_en <= '1';
				IF (writing /= "00") THEN
					writing <= writing - 1;
				ELSE
					--IF (writing = '0' AND switch_rdy = '0') THEN
					--END IF;
					IF (writing = "00" AND switch_rdy = '1') THEN
						ramrom_addr <= ramrom_addr + 1;
						mem_ptr <= ramrom_addr;
						y <= TEST;--*************************************
					END IF;
				END IF;
			ELSIF (y = READ) THEN
				IF (test_delay = X"0") THEN --X"2FAF080" = 1 sec@50MHz****
					test_delay <= (OTHERS => '0');
					y <= IDLE;
				ELSE
					test_delay <= test_delay + 1;
				END IF;
			ELSIF (y = TEST) THEN
				IF (test_delay = X"0") THEN--**********************
					test_delay <= (OTHERS => '0');
					IF (test_index <= 16) THEN
						test_index <= (test_index + 1);
						lookup_req <= '1';
						writing <= "01";
						y <= WRITE;
					ELSE
						test_index <= 0;
						y <= IDLE;
					END IF;
				ELSE
					test_delay <= test_delay + 1;
				END IF;
			END IF;
		END IF;
	END PROCESS;
END Behavior;